package org.itboys.mobile.service.mongo.weixin;

import com.aliyuncs.exceptions.ClientException;
import org.itboys.commons.ErrorException;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.entity.mongo.SundayValiDateCode;
import org.itboys.mobile.util.PhoneUtil;
import org.itboys.mobile.util.RandomUtil;
import org.itboys.mobile.util.SMS.AliyunSMSUtil;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseMongoService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作者：zzq
 * 时间：2017/8/23
 * 描述：搜鸟私厨_
 */
@Service
public class SundayValicodedateService extends BaseMongoService<SundayValiDateCode>{
    @Resource(name = "mobileDs")
    private MongoDataSource yefuDataSource;
    @Override
    protected MongoDataSource getMongoDataSource() {
        return yefuDataSource;
    }

    @Override
    protected Class<SundayValiDateCode> getEntityClass() {
        return SundayValiDateCode.class;
    }

    /**
     * 发送验证码
     * @param mobile
     */
    public void sendValidateCode(String mobile) throws ClientException {
        if (!PhoneUtil.isMobileNumber(mobile)) {
            throw new ErrorException("请填入正确手机号.");
        }
        //删除用户验证码
        Map<String,Object> param = new HashMap<String, Object>();
        param.clear();
        param.put("isDeleted", SundayCommonConstants.NO);
        param.put("mobile", mobile);
        super.delete(param);
        // 生成验证码
        String code = RandomUtil.generateRandomNumber(4);
        // 发送    待补充
        AliyunSMSUtil.sundaySendSms(mobile,code);
        //DaYuSMSUtils.sendSMS(mobile,code);
        // MessageUtils.sendMessage(mobile,"您的验证码是："+code);
        System.out.println(new Date().getTime()+"当前验证码为============="+code);
        // 保存验证码
        super.save(new SundayValiDateCode(mobile, code));
    }
    /**
     * 检验验证码.校验后删除验证码
     * @param mobile
     * @param code
     */
    public void checkValidateCode(String mobile,String code){
        Map<String,Object> param=new HashMap<String,Object>();
        param.put("isDeleted",SundayCommonConstants.NO);
        param.put("mobile",mobile);
        if (!PhoneUtil.isMobileNumber(mobile)) {
            throw new ErrorException("请填入正确手机号");
        }
        List<SundayValiDateCode> codes = super.list(param);
        if(codes!=null&&codes.size()>1){
            throw new ErrorException("数据错误，请重新获取验证码。");
        }else if(codes==null||codes.size()<1){
            throw new ErrorException("验证码错误。");
        }else{
            if(!code.equals(codes.get(0).getCode())){
                throw new ErrorException("验证码错误。");
            }
        }
        //校验完成后删除验证码
        param.clear();
        param.put("mobile", mobile);
        super.delete(param);
    }
}
